﻿using System;
using System.Collections.Generic;
using System.Linq;
using InsuranceAdjuster.Services;
using InsuranceAdjuster.Web.Models;

namespace InsuranceAdjuster.OccasionallyConnected.Messages
{
    public class GetStatesMessage : Message
    {
        public GetStatesMessage()
        {
            this.CacheRules = MessageDataSource.CacheAndServer | MessageDataSource.FromServerOnlyIfNoCacheOption;
        }

        protected override void OnlineOperation()
        {
            MarkAsyncStarted();
            GetDataService().GetStates(entities =>
            {
                for (int x = 0; x < entities.Count; x++)
                    this.ResponseEntities.Add("Result" + x, new MessageResult(Verb.Read, Origin.Server, entities[x]));

                MarkAsyncFinished();
                });

        }
        protected override List<MessageResult> OfflineOperation(IObjectStore objectStore)
        {
            return objectStore.GetEntities<State>().Select(x => new MessageResult(Verb.Read, Origin.Cache, x))
                                            .ToList();
        }
        protected override List<MessageResult> CompileServerResults() {
            return this.ResponseEntities.Select(x => x.Value).ToList();
        }
    }
}
